package cn.wolfcode.wolf2w.interceptor;

import cn.wolfcode.wolf2w.annotation.RequireLogin;
import cn.wolfcode.wolf2w.cache.service.IUserInfoRedisService;
import cn.wolfcode.wolf2w.domain.UserInfo;
import cn.wolfcode.wolf2w.util.JsonResult;
import com.alibaba.fastjson.JSON;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class CheckLoginInterceptor implements HandlerInterceptor {
    @Autowired
    private IUserInfoRedisService userInfoRedisService;
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        //判断静态资源,如果是HandlerMethod表示该请求请求的是controller中的方法
        if(!(handler instanceof HandlerMethod)){
            return true;
        }
        //hm表示当前请求的controller方法
        HandlerMethod hm = (HandlerMethod) handler;

        //如果方法上面贴有RequireLogin注解，需要判断登陆状态，否则直接放行
        if(hm.hasMethodAnnotation(RequireLogin.class)){
            String token = request.getHeader("token");
            UserInfo u = userInfoRedisService.getUserByToken(token);
            if(u == null){
                JsonResult ret = JsonResult.noLogin();
                response.setContentType("application/json; charset=utf-8");
                response.getWriter().write(JSON.toJSONString(ret));
                return false;
            }
            else{
                return true;
            }
        }
        else{
            return true;
        }


    }
}
